package com.agnes.phone.listener;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.agnes.phone.AppContext;

import static android.content.Context.TELEPHONY_SERVICE;

public class PhoneUtil {
    private static volatile PhoneUtil instance;

    private TelephonyManager mTelephonyManager;
    private PhoneStateListener mListener;
    private Context mAppContex;


    private PhoneUtil() {
    }

    public static PhoneUtil getInstance() {
        if (instance == null) {
            synchronized (PhoneUtil.class) {
                if (instance == null) {
                    instance = new PhoneUtil();

                }
            }
        }
        return instance;
    }


    public void registerPhoneState(Context context) {
        getTelephonyManager();
        mListener = new MyPhoneStateListener(context);
        if (mTelephonyManager != null) {
            mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    /**
     * 取消来电的电话状态监听服务
     */
    public void unRegisterPhoneState() {
        if (mTelephonyManager != null && mListener != null) {
            mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
        }
    }



    private void getTelephonyManager() {
        mAppContex = AppContext.getContext();
        mTelephonyManager = (TelephonyManager) mAppContex.getSystemService(TELEPHONY_SERVICE);
    }

}
